package com.myccb.app.view.activity;

import android.content.Intent;
import android.graphics.drawable.Drawable;
import android.os.AsyncTask;
import android.os.Bundle;
import android.text.Editable;
import android.text.InputFilter;
import android.text.InputType;
import android.text.Spanned;
import android.text.TextWatcher;
import android.util.Log;
import android.view.View;
import android.widget.TextView;
import android.widget.Toast;

import com.myccb.app.AppStatus;
import com.myccb.app.R;
import com.myccb.app.base.RequestManager;
import com.myccb.app.base.BaseActivity;
import com.myccb.app.util.BCNumUtil;
import com.myccb.app.util.NumberUtil;
import com.myccb.app.widget.CommonDialog;
import com.myccb.app.widget.CommonToolBar;
import com.myccb.app.widget.EditTextClearable;
import com.myccb.app.widget.LoadingCountdownDialog;

import org.json.JSONException;
import org.json.JSONObject;

import java.math.BigDecimal;
import java.util.HashMap;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

public class TransferActivity extends BaseActivity {

    private EditTextClearable etc_transferAmount;
    private Drawable currencyDrawable;
    private TextView transferAmountChinese;
    private TextView tv_fromCardNum;
    private TextView tv_fromCardInfo;
    private EditTextClearable etc_toAccountName;
    private EditTextClearable etc_toAccountNum;
    private TextView tv_toBankName;

    private EditTextClearable etc_transferMsg;
    private String balance;
    private String fromBCNum;
    private TextView transferBtn;

    private LoadingCountdownDialog loadingCountdownDialog;
    private CommonDialog errorMsgDialog;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        if (!AppStatus.isLogin){
            AppStatus.startLoginActivity(this);
        }
        setContentView(R.layout.activity_transfer);
        initView();
        initData();
    }
    @Override
    protected void onResume() {
        super.onResume();
        initData();
    }
    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data)
    {
        super.onActivityResult(requestCode, resultCode, data);
        if (requestCode == 1 && resultCode == 2)
        {
            if (!data.getStringExtra("status").equals("success"))
                finish();
        }
    }

    private void initView(){
        CommonToolBar commonToolBar=findViewById(R.id.common_toolbar);
        setSupportActionBar(commonToolBar.getToolbar());
        commonToolBar.setOnLeftButtonClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                finish();
                overridePendingTransition(android.R.anim.fade_in,android.R.anim.slide_out_right);
            }
        });

        tv_fromCardNum=findViewById(R.id.pay_card_num);
        tv_fromCardInfo=findViewById(R.id.pay_card_info);

        etc_toAccountName=findViewById(R.id.transfer_to_name);
        etc_toAccountNum=findViewById(R.id.transfer_to_num);

        tv_toBankName=findViewById(R.id.select_bank);
        etc_transferMsg=findViewById(R.id.transfer_msg);


        etc_transferAmount=findViewById(R.id.transfer_amount);

        etc_toAccountNum.addOnTextChangeListener(new TransferTextWatch());
        etc_toAccountName.addOnTextChangeListener(new TransferTextWatch());
        etc_transferAmount.addOnTextChangeListener(new TransferTextWatch());

        transferAmountChinese=findViewById(R.id.transfer_amount_chinese);
        etc_transferAmount.setInputType(InputType.TYPE_NUMBER_FLAG_DECIMAL|InputType.TYPE_CLASS_NUMBER);

        etc_transferAmount.setFilters(new InputFilter[]{new InputFilter() {
            @Override
            public CharSequence filter(CharSequence source, int start, int end, Spanned dest, int dstart, int dend) {
                int keep = 16 - (dest.length() - (dend - dstart));
                if (keep <= 0) {
                    return "";
                }
                if(source.equals(".") && dest.toString().length() == 0){
                    return "0.";
                }
                if(dest.toString().contains(".")){
                    int index = dest.toString().indexOf(".");
                    int length = dest.toString().substring(index).length();
                    if(length == 3){
                        return "";
                    }
                }
                return null;
            }
        }});


        etc_transferAmount.addOnFocusChangeListener(new View.OnFocusChangeListener() {
            @Override
            public void onFocusChange(View v, boolean hasFocus) {
                EditTextClearable etc=(EditTextClearable)v;
                if (hasFocus){
                    etc.setHint("");
                    etc.setTextSize(20);
                    if (etc.getText().toString().length()<1){
                        etc.setText("¥");
                        etc.setSelection(etc.getText().length());
                    }
                    etc_transferAmount.setTextWatcher(new TextWatcher() {
                        @Override
                        public void beforeTextChanged(CharSequence s, int start, int count, int after) {
                        }
                        @Override
                        public void onTextChanged(CharSequence s, int start, int before, int count) {
                            if (!s.toString().startsWith("¥")){
                                transferAmountChinese.setText("");
                                etc_transferAmount.setText("¥"+s.toString());
                                etc_transferAmount.setSelection(etc_transferAmount.getText().length());
                                return;
                            }
                            if (s.toString().startsWith(".")){
                                transferAmountChinese.setText("");
                                etc_transferAmount.setText("0"+s.toString());
                                etc_transferAmount.setSelection(etc_transferAmount.getText().length());
                                return;
                            }
                            s=s.toString().replace("¥","");
                            if (s.toString().equals(""))
                                return;
                            Pattern pattern = Pattern.compile("^(\\d{0,16})(\\.\\d{0,2})?$");
                            Matcher matcher = pattern.matcher(s.toString());
                            if (matcher.matches()){
                                transferAmountChinese.setText(NumberUtil.number2CNMontrayUnit(new BigDecimal(s.toString())));
                                return;
                            }
                        }
                        @Override
                        public void afterTextChanged(Editable s) {
                        }
                    });
                }
                else {
                    if (etc.getText().toString().length()<1||etc.getText().toString().equals("¥")){
                        etc.setHint("请输入转账金额");
                        etc_transferAmount.setTextWatcher(null);
                        etc.setText("");
                        etc.setTextSize(12);}
                        transferAmountChinese.setText("");
                }
            }
        });

        etc_transferMsg.setOnFocusChangeListener(new View.OnFocusChangeListener() {
            @Override
            public void onFocusChange(View v, boolean hasFocus) {
                if (hasFocus){
                    etc_transferMsg.setHint("");
                }
                else {
                    if (etc_transferMsg.getText().length()<1)
                        etc_transferMsg.setHint("添加转账附言");
                }
            }
        });
        currencyDrawable=getResources().getDrawable(R.mipmap.currency);
        currencyDrawable.setBounds(0,0,currencyDrawable.getIntrinsicWidth(),currencyDrawable.getIntrinsicHeight());

        loadingCountdownDialog=new LoadingCountdownDialog(this);
        errorMsgDialog=new CommonDialog(this);

        transferBtn=findViewById(R.id.transfer_btn);
        transferBtn.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                String[] values=new String[6];
                String num=etc_toAccountNum.getText().toString();
                if (NumberUtil.isPhoneNum(num)){
                    values[0]="1";
                    values[1]="1";
                }
                else
                if (BCNumUtil.getNameOfBank(num).equals("")){
                    showErrorMsg("银行卡号输入有误！",0);
                    return;
                }
                else {
                    values[0]="2";
                    if (BCNumUtil.getNameOfBank(num).contains("建设银行")){
                        values[1]="1";
                    }
                    else
                        values[1]="0";
                }
                values[2]=num;
                values[3]=tv_toBankName.getText().toString();
                values[4]=etc_transferAmount.getText().toString().replace("¥","");
                values[5]=etc_transferMsg.getText().toString();
                new TransferTask().execute(values);
            }
        });
    }

    private void initData(){
        if (AppStatus.isLogin){
            new GetUserInfoTask().execute();
        }
    }
    private class GetUserInfoTask extends AsyncTask<Integer, Void, Integer> {
        @Override
        protected void onPreExecute() {

            super.onPreExecute();
            loadingCountdownDialog.show(30);

        }
        @Override
        protected Integer doInBackground(Integer... integers) {
            HashMap<String,String> postParams=new HashMap<>();
            postParams.put("item","all");
            String result= RequestManager.getInstance(getApplicationContext()).requestSyn("getUserInfo.php",RequestManager.TYPE_POST_FORM,postParams);
            Log.d("index",result);
            JSONObject jb = null;
            try {
                jb = new JSONObject(result);
                int status=jb.getInt("status");
                if(status==0){
                    int code=jb.getInt("code");
                    return code*10;
                }
                else if (status==1){
                    jb=jb.getJSONObject("result");
                    if (jb!=null){
                        if (jb.has("mainBCNum"))
                            fromBCNum=jb.getString("mainBCNum");
                        if (jb.has("balance"))
                            balance=jb.getString("balance");
                    }
                }
            } catch (JSONException e) {
                e.printStackTrace();
            }
            return 0;
        }

        @Override
        protected void onPostExecute(Integer integer) {
            super.onPostExecute(integer);
            loadingCountdownDialog.dismiss();
            if (integer/10!=0){
                /*showError(integer/10);*/
                return;
            }
            switch (integer){
                case 0:
                    tv_fromCardInfo.setText("人民币 活期储蓄  "+balance);
                    tv_fromCardNum.setText(fromBCNum.substring(0,4)+"***"+fromBCNum.substring(fromBCNum.length()-4,fromBCNum.length()));
            }
        }
    }

    class TransferTask extends AsyncTask<String, String, Integer> {

        private boolean transferSuccess;

        @Override
        protected void onPreExecute() {
            loadingCountdownDialog.show(30);
        }

        @Override
        protected Integer doInBackground(String... values) {
            int code = 0;
            HashMap<String, String> postParams = new HashMap<>();
            postParams.put("type", values[0]);
            //postParams.put("vcode",vcode);
            postParams.put("isIntra", values[1]);
            postParams.put("toNum", values[2]);
            postParams.put("toName", values[3]);
            postParams.put("amount", values[4]);
            postParams.put("summary", values[5]);

            String result = RequestManager.getInstance(getApplicationContext()).requestSyn("transfer.php", RequestManager.TYPE_POST_FORM, postParams);

            Log.d("login", result);

            JSONObject jb = null;
            try {
                jb = new JSONObject(result);
                int status = jb.getInt("status");
                if (status == 0) {
                    transferSuccess = false;
                    code = jb.getInt("code");
                } else if (status == 1) {
                    transferSuccess = true;
                }
            } catch (JSONException e) {
                e.printStackTrace();
            }
            return code;
        }

        @Override
        protected void onPostExecute(Integer code) {
            loadingCountdownDialog.dismiss();
            if (transferSuccess) {
                Toast.makeText(getApplicationContext(),"转账成功！", Toast.LENGTH_LONG).show();
                finish();
            } else {
                switch (code){
                    case 5:
                        showErrorMsg("您不能为自己转账！",code);
                        break;
                    case 9:
                        showErrorMsg("转账失败:账户余额不足！",code);
                }
                //showLoginError(code);
            }
        }
    }

    private void showErrorMsg(String msg,int code){
        errorMsgDialog.showMessage(msg,"错误代码:"+code);
    }

    private class TransferTextWatch implements EditTextClearable.OnTextChangeListener{
        @Override
        public void onTextChanged(CharSequence s, int start, int before, int count) {
            String num=etc_toAccountNum.getText().toString();
            if (num.length()>=16){
                if (BCNumUtil.getNameOfBank(num).equals(""))
                    tv_toBankName.setText("未找到相关银行");
                else
                    tv_toBankName.setText(BCNumUtil.getNameOfBank(num));
            }
            if (NumberUtil.isPhoneNum(num))
                tv_toBankName.setText("中国建设银行");
            if (etc_toAccountName.getText().length()<1||etc_toAccountNum.getText().length()<1||etc_transferAmount.getText().length()<1||etc_transferAmount.getText().toString().equals("¥")){
                transferBtn.setEnabled(false);
                return;
            }

            if (!NumberUtil.isPhoneNum(num)&& BCNumUtil.getNameOfBank(num).equals("")){
                transferBtn.setEnabled(false);
                return;
            }


            transferBtn.setEnabled(true);
        }
    }
}
